<template>
  <q-form ref="form" @submit="onSubmit" class="q-gutter-md q-pb-xl">
    <formInput ref='formInput' :fieldlist="formFields" multipleCol />

    <history v-if="mode === 'edit'" class="q-mb-xl" :data="historyData" :escape="historyEscape" :tableFields="tableFields" />

    <q-page-sticky position="bottom" :offset="[0, 28]">
      <q-btn label="保存" type="submit" color="primary" class="btn-fixed-width" icon="save" :loading="saving" v-if="canSave" />
      <q-btn label="返回" @click="onReset" color="primary" outline class="q-ml-md bg-white" />
    </q-page-sticky>
  </q-form>

  <dialogForm ref="addCustomerForm" :config="addCustomerConfig" :size="addCustomerConfig.size" :column="addCustomerConfig.column" :buttonLabel="['确定', '关闭']" />
</template>

<script>
import { defineComponent } from 'vue';
import formInput from 'src/components/FormInput.vue';
import { detailPageMix } from 'src/lib/mixin.js';
import history from 'src/components/history.vue'
import { isNumber } from 'src/lib/utils.js';
import { useMeta } from 'quasar';
import { useStore } from 'stores/store';
import dialogSelectTable from 'src/components/DialogSelectTable.vue';

import moment from 'moment';
import dialogForm from 'src/components/DialogInputForm.vue';

export default defineComponent({
  name: 'saleDetail',
  setup (props, context) {
    const $store = useStore();
    const modelLabel = '销售单';
    const moduleName = 'sale';
    const detailApi = `/c2/tenant/${moduleName}/detail`; // 明细数据接口
    const createApi = `/c2/tenant/${moduleName}/create`; // 新建数据接口
    const updateApi = `/c2/tenant/${moduleName}/update`; // 更新数据接口

    useMeta({
      // 设置文件标题
      title: `${modelLabel}详情 - ${$store.siteConfig.appName} - 木多鱼系列`
    });

    return {
      modelLabel,
      moduleName,
      detailApi,
      createApi,
      updateApi
    }
  },
  components: {
    formInput,
    history,
    dialogSelectTable,
    dialogForm
  },
  mixins: [detailPageMix],
  data () {
    const self = this;
    return {
      formFields: {
        bill_no: { type: 'input', label: '销售编号', value: '', readonly: true },
        type: { type: 'select', label: '销售单类型', value: '', dict: 'saleType', readonly: true },
        status: { type: 'select', label: '状态', value: '', dict: 'saleStatus', clearable: false, readonly: false },
        customer_uid: {
          type: 'select',
          label: '客户 *',
          value: '',
          options: [],
          dict: 'customer',
          rules: [val => !!val || '请输入客户'],
          btn: {
            hint: '若列表中没有找到客户，请先添加客户',
            icon: 'add',
            color: 'secondary',
            flat: true,
            disable: false,
            fn (field) {
              for (const [key, field] of Object.entries(self.addCustomerConfig.fields)) {
                field.value = '';
              }

              self.$refs.addCustomerForm.show().then(formData => {
                if (formData) {
                  self.$axios.post('/c2/tenant/customer/create', { formData }).then(({ data }) => {
                    if (data.result === 'fail') {
                      self.$q.notify({
                        message: data.message || '保存失败',
                        color: 'negative',
                        icon: 'error',
                        position: 'top',
                        timeout: 5000,
                        html: data.message && data.message.indexOf('<br>') >= 0
                      });
                    } else {
                      self.initDict(['customer']).then(() => {
                        self.formFields.customer_uid.options = self.dictionary.customer;
                        self.formFields.customer_uid.value = self.dictionary.customer.find(v => v.value == data.uid);
                      });
                    }
                  });
                }
              });
            }
          },
          readonly: false
        },
        consignee: { type: 'input', label: '联系人', value: '', readonly: false },
        tel: { type: 'input', label: '联系电话', value: '', readonly: false },
        address: { type: 'input', label: '地址', value: '', readonly: false },

        remark: { type: 'input', label: '备注', value: '', autogrow: true, readonly: false },

        t_sale_details: {
          type: 'table',
          label: '销售明细',
          value: [],
          editmode: ['new', 'edit', 'delete'],
          columns: [
            { name: 'id', field: 'id', visible: false, editConfig: {} },
            { name: 'material_unit', field: 'material_unit', visible: false, editConfig: {} },
            { name: 'material_name_model', field: 'material_name_model', visible: false, editConfig: {} },
            { name: 'material_image', label: '图片', field: 'material_image', isImage: true, align: 'center', editConfig: {} },
            {
              name: 'material_uid',
              label: '货物',
              field: 'material_uid',
              align: 'center',
              format: (val, row) => row.material_name_model,
              editConfig: {
                type: 'select',
                value: '',
                dict: 'material',
                rules: [val => !!val || '请输入货物'],
                dataRender (field, val) {
                  if (val && val.length > 0 && val[0]) {
                    field.material_image.value = val[0].default_image;
                    field.material_uid.value = val[0].value;
                    field.material_name_model.value = val[0].label;
                    field.material_unit.value = val[0].material_unit;
                    field.amount.suffix = val[0].material_unit;

                    const amount = field.amount.value || 0;
                    const price = field.price.value || 0;
                    const tax_rate = field.tax_rate.value || 0;
                    field.money.value = Number((amount * price * (1 + tax_rate / 100)).toFixed(3));
                  }
                },
                preRender: true,
                readonly: false
              }
            },
            {
              name: 'amount',
              label: '数量',
              field: 'amount',
              align: 'center',
              format: (val, row) => `${Number(val)} ${row.material_unit || ''}`,
              editConfig: {
                type: 'input',
                value: '',
                rules: [val => isNumber(val) || '请输入数值型数量'],
                suffix: '{material_unit}',
                dataRender (field, val) {
                  const amount = field.amount.value || 0;
                  const price = field.price.value || 0;
                  const tax_rate = field.tax_rate.value || 0;

                  field.money.value = Number((amount * price * (1 + tax_rate / 100)).toFixed(3));
                },
                readonly: false
              }
            },
            {
              name: 'price',
              label: '单价',
              field: 'price',
              align: 'center',
              format: (val, row) => `${Number(val).toFixed(2)} 元`,
              editConfig: {
                type: 'input',
                value: '',
                rules: [val => isNumber(val) || '请输入数值型单价'],
                prefix: '',
                suffix: '元',
                dataRender (field, val) {
                  const amount = field.amount.value || 0;
                  const price = field.price.value || 0;
                  const tax_rate = field.tax_rate.value || 0;

                  field.money.value = Number((amount * price * (1 + tax_rate / 100)).toFixed(3));
                },
                readonly: false
              }
            },
            {
              name: 'tax_rate',
              label: '税率',
              field: 'tax_rate',
              align: 'center',
              format: (val, row) => `${Number(val)} %`,
              editConfig: {
                type: 'input',
                value: '0',
                default: 13,
                suffix: '%',
                rules: [val => isNumber(val) || '请输入数值型税率'],
                dataRender (field, val) {
                  const amount = field.amount.value || 0;
                  const price = field.price.value || 0;
                  const tax_rate = field.tax_rate.value || 0;

                  field.money.value = Number((amount * price * (1 + tax_rate / 100)).toFixed(3));
                },
                readonly: false
              }
            },
            {
              name: 'money',
              label: '金额',
              field: 'money',
              align: 'center',
              format: (val, row) => `${Number(val).toFixed(2)} 元`,
              editConfig: { type: 'input', value: '', suffix: '元', readonly: true }
            },
            {
              name: 'remark',
              label: '备注',
              field: 'remark',
              align: 'center',
              editConfig: { type: 'input', value: '', autogrow: true, readonly: false }
            }
          ]
        },

        total_money: { type: 'input', label: '销售总金额', value: '', prefix: '', suffix: '', readonly: true }
      },
      addCustomerConfig: {
        title: '添加客户档案',
        size: 'md',
        column: 2,
        fields: {
          images: { type: 'image', label: '客户图片', value: [], fullwidth: true },
          sep1: { type: 'separator', label: '客户信息', fullwidth: true },
          nickname: { type: 'input', label: '客户名称 *', value: '', rules: [val => !!val || '请输入客户名称', this.checkCustomer] },
          company: { type: 'input', label: '开票抬头', value: '' },
          contact: { type: 'input', label: '联系人', value: '' },
          tel: { type: 'input', label: '电话', value: '', autogrow: true },
          email: { type: 'input', label: '邮箱', value: '', autogrow: true },
          address: { type: 'input', label: '地址', value: '', autogrow: true },
          remark: { type: 'input', label: '备注', value: '', fullwidth: true }
        }
      }
    };
  },
  async created () {
    // 判断是否有新增客户的权限
    if (!(this.rights.customer && this.rights.customer.func && this.customer.supplier.add)) {
      delete this.formFields.customer_id.btn;
    }
  },
  mounted () {
    if (this.mode === 'add') {
      this.formFields.type.value = 'enter';
      this.formFields.status.value = 'normal';
    } else if (this.mode === 'edit') {
      this.refreshData(() => {
        if (this.data.type === 'shop') {
          this.formFields.customer_uid.label = '客户';
          delete this.formFields.customer_uid.rules;
          this.formFields.customer_uid.readonly = true;
        }
      });
    }

    // 无客户新增权限，删除新增按钮
    if (!(this.rights.customer && this.rights.customer.func && this.rights.customer.add)) {
      delete this.formFields.customer_uid.btn;
    }
  },
  methods: {
    async onSubmit () {
      if (!this.formFields.t_sale_details.value || this.formFields.t_sale_details.value.length < 1) {
        this.$q.notify({
          message: '明细不能为空',
          color: 'negative',
          icon: 'error',
          position: 'center',
          timeout: 5000
        });
        return;
      }
      const err = this.$refs.formInput.validateTable();
      if (err) {
        this.$q.notify({
          message: err,
          color: 'negative',
          icon: 'error',
          position: 'top',
          timeout: 2000
        });
        return;
      }

      this.$refs.formInput.validateAll();
      this.$nextTick(() => {
        this.$refs.form.validate().then(ot => {
          if (ot) {
            this.saving = true;
            this.$refs.formInput.getFormData().then(data => {
              this.saveData(data);
            }).catch(e => {
              console.log(e);
              this.saving = false
            });
          }
        });
      });
    },
    checkCustomer (code) {
      return new Promise((resolve, reject) => {
        this.$axios.post('/c/system/checkRepeatCode', { code: 'CU', values: { nickname: code } }).then(({ data }) => {
          resolve(data ? '客户名称重复' : null);
        });
      });
    }
  },
  computed: {
    detailValue () {
      return typeof this.formFields.t_sale_details.value === 'object' ? JSON.stringify(this.formFields.t_sale_details.value) : this.formFields.t_sale_details.value;
    }
  },
  watch: {
    'formFields.customer_uid.value' (val) {
      if (val) {
        const uid = typeof val === 'object' ? val.value : val;
        this.$axios.get('/c2/tenant/customer/simple', { params: { uid } }).then(({ data }) => {
          this.formFields.consignee.value = data.contact;
          this.formFields.tel.value = data.tel;
          this.formFields.address.value = data.address;
        });
      }
    },
    detailValue (val) { // 明细有变动，重新统计总金额
      const detailValue = JSON.parse(val);
      let total_money = 0;
      for (const row of detailValue) {
        total_money += Number(row.money);
      }

      this.formFields.total_money.value = total_money.toFixed(2);
    }
  }
});
</script>
